import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';

const Duration _kIndicatorScaleDuration = Duration(milliseconds: 200);

class CustomLottieHeader extends Header {
    /// Key
    final Key? key;
    // 背景颜色
    final Color? backgroundColor;

    final LinkHeaderNotifier linkNotifier = LinkHeaderNotifier();

    CustomLottieHeader({
        this.key,
        this.backgroundColor = Colors.transparent,
        bool enableHapticFeedback = true,
        Duration completeDuration = const Duration(seconds: 1),
    }) : super(
            extent: 80.0,
            triggerDistance: 120.0,
            float: false,
            enableHapticFeedback: enableHapticFeedback,
            enableInfiniteRefresh: false,
            completeDuration: completeDuration,
        );

    @override
    Widget contentBuilder(
        BuildContext context,
        RefreshMode refreshState,
        double pulledExtent,
        double refreshTriggerPullDistance,
        double refreshIndicatorExtent,
        AxisDirection axisDirection,
        bool float,
        Duration? completeDuration,
        bool enableInfiniteRefresh,
        bool success,
        bool noMore) {
        // 不能为水平方向以及反向
        assert(axisDirection == AxisDirection.down,
            'Widget can only be vertical and cannot be reversed');
        linkNotifier.contentBuilder(
            context,
            refreshState,
            pulledExtent,
            refreshTriggerPullDistance,
            refreshIndicatorExtent,
            axisDirection,
            float,
            completeDuration,
            enableInfiniteRefresh,
            success,
            noMore);
        return LottieHeader(
            key: key,
            linkNotifier: linkNotifier,
            backgroundColor:backgroundColor!
        );
    }
}

class LottieHeader extends StatefulWidget {
    final LinkHeaderNotifier linkNotifier;
    final Color backgroundColor;
    LottieHeader({Key? key,required this.linkNotifier,required this.backgroundColor}) : super(key: key);

    @override
    _LottieHeaderState createState() => _LottieHeaderState();
}

class _LottieHeaderState extends State<LottieHeader> with SingleTickerProviderStateMixin{

    RefreshMode get _refreshState => widget.linkNotifier.refreshState;
    double get _pulledExtent => widget.linkNotifier.pulledExtent;
    double get _indicatorExtent => widget.linkNotifier.refreshIndicatorExtent;
    double get _refreshTriggerPullDistance => widget.linkNotifier.refreshTriggerPullDistance;
    bool get _noMore => widget.linkNotifier.noMore;

    late final AnimationController lottieController;

    double totalFrame=0;

    @override
    void initState() {
        super.initState();

        lottieController = AnimationController(vsync: this)..addStatusListener((status) {
            if(status==AnimationStatus.completed){
                lottieController.reset();
            }
        });
        widget.linkNotifier.addListener(() {
            print(widget.linkNotifier.pulledExtent);
            print(widget.linkNotifier.refreshIndicatorExtent);
            if(widget.linkNotifier.pulledExtent<widget.linkNotifier.refreshIndicatorExtent){
                // double target=(widget.linkNotifier.pulledExtent/widget.linkNotifier.refreshIndicatorExtent)*totalFrame;
                // LogUtil.v(target,tag: "target");
                // lottieController.animateTo(0.2,duration: Duration(milliseconds: 300));
                // lottieController.forward(from: target);
            }
            // if(widget.linkNotifier.refreshState==RefreshMode.refresh){
            //     lottieController.repeat();
            // }
            // if(widget.linkNotifier.refreshState==RefreshMode.refreshed){
            //     lottieController.reverse();
            // }
        });
    }

    @override
    Widget build(BuildContext context) {
        return Container(
            width: double.infinity,
            height: _pulledExtent,
            color: widget.backgroundColor,
            child: Center(
                child: Lottie.network(
                    'https://assets9.lottiefiles.com/packages/lf20_bgi3cnlc.json',
                    width: double.infinity,
                    height: _refreshTriggerPullDistance,
                    controller:lottieController,
                    fit:BoxFit.contain,
                    onLoaded: (composition){
						lottieController..duration = composition.duration..reset()..repeat();
                        // LogUtil.v(composition.bounds,tag: "composition.bounds");
                        // LogUtil.v(composition.frameRate,tag: "composition.frameRate");
                        // LogUtil.v(composition.seconds,tag: "composition.seconds");

                        // LogUtil.v(lottieController.lowerBound,tag: "lottieController.lowerBound");
                        // LogUtil.v(lottieController.upperBound,tag: "lottieController.upperBound");
                    },

                ),
            ),
        );
    }
}

// class MaterialHeaderWidget extends StatefulWidget {
//   final double displacement;
//   final Animation<Color> valueColor;
//   final Color backgroundColor;
//   final LinkHeaderNotifier linkNotifier;

//   const MaterialHeaderWidget({
//     Key key,
//     this.displacement,
//     this.valueColor,
//     this.backgroundColor,
//     this.linkNotifier,
//   }) : super(key: key);

//   @override
//   MaterialHeaderWidgetState createState() {
//     return MaterialHeaderWidgetState();
//   }
// }
// class MaterialHeaderWidgetState extends State<MaterialHeaderWidget>
//     with TickerProviderStateMixin<MaterialHeaderWidget>{
//   static final Animatable<double> _oneToZeroTween =
//   Tween<double>(begin: 1.0, end: 0.0);

//   RefreshMode get _refreshState => widget.linkNotifier.refreshState;
//   double get _pulledExtent => widget.linkNotifier.pulledExtent;
//   double get _riggerPullDistance =>widget.linkNotifier.refreshTriggerPullDistance;
//   Duration get _completeDuration =>
//       widget.linkNotifier.completeDuration;
//   AxisDirection get _axisDirection => widget.linkNotifier.axisDirection;

//   AnimationController _scaleController;
//   Animation<double> _scaleFactor;

//   @override
//   void initState() {
//     super.initState();
//     _scaleController = AnimationController(vsync: this);
//     _scaleFactor = _scaleController.drive(_oneToZeroTween);
//   }

//   @override
//   void dispose() {
//     super.dispose();
//     _scaleController.dispose();
//   }

//   bool _refreshFinish = false;
//   set refreshFinish(bool finish) {
//     if (_refreshFinish != finish) {
//       if (finish) {
//         Future.delayed(_completeDuration
//             - Duration(milliseconds: 300), () {
//           if (mounted) {
//             _scaleController.animateTo(1.0, duration: _kIndicatorScaleDuration);
//           }
//         });
//         Future.delayed(_completeDuration, () {
//           _refreshFinish = false;
//           _scaleController.animateTo(0.0, duration: Duration(milliseconds: 10));
//         });
//       }
//       _refreshFinish = finish;
//     }
//   }

//   @override
//   Widget build(BuildContext context) {
//     bool isVertical = _axisDirection == AxisDirection.down
//         || _axisDirection == AxisDirection.up;
//     bool isReverse = _axisDirection == AxisDirection.up
//         || _axisDirection == AxisDirection.left;
//     double indicatorValue = _pulledExtent / (_riggerPullDistance / 0.75);
//     indicatorValue = indicatorValue < 0.75 ? indicatorValue : 0.75;
//     if (_refreshState == RefreshMode.refreshed) {
//       refreshFinish = true;
//     }
//     return Container(
//       height: isVertical ? _refreshState == RefreshMode.inactive
//           ? 0.0 : _pulledExtent : double.infinity,
//       width: !isVertical ? _refreshState == RefreshMode.inactive
//           ? 0.0 : _pulledExtent : double.infinity,
//       child: Stack(
//         children: <Widget>[
//           Positioned(
//             top: isVertical ? isReverse ? 0.0 : null : 0.0,
//             bottom: isVertical ? !isReverse ? 0.0 : null : 0.0,
//             left: !isVertical ? isReverse ? 0.0 : null : 0.0,
//             right: !isVertical ? !isReverse ? 0.0 : null : 0.0,
//             child: Container(
//               padding: EdgeInsets.only(
//                 top: isVertical ? isReverse ? 0.0 : widget.displacement : 0.0,
//                 bottom: isVertical ? !isReverse ? 0.0
//                     : widget.displacement : 0.0,
//                 left: !isVertical ? isReverse ? 0.0 : widget.displacement : 0.0,
//                 right: !isVertical ? !isReverse ? 0.0
//                     : widget.displacement : 0.0,
//               ),
//               alignment: isVertical ? isReverse ? Alignment.topCenter
//                   : Alignment.bottomCenter : isReverse
//                   ? Alignment.centerLeft : Alignment.centerRight,
//               child: ScaleTransition(
//                 scale: _scaleFactor,
//                 child: RefreshProgressIndicator(
//                   value: _refreshState == RefreshMode.armed
//                       || _refreshState == RefreshMode.refresh
//                       || _refreshState == RefreshMode.refreshed
//                       || _refreshState == RefreshMode.done
//                       ? null
//                       : indicatorValue,
//                   valueColor: widget.valueColor,
//                   backgroundColor: widget.backgroundColor,
//                 ),
//               ),
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }
